﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Wpf.Ui;
using Wpf.Ui.Controls;
using Wpf.Ui.Extensions;
using XC.Managers.Accounts;
using XC.WpfHost.Extensions;
using XC.WpfHost.Services.Contracts;
using XC.WpfHost.Views;

namespace XC.WpfHost.ViewModels
{
    /// <summary>
    /// 登录模型
    /// </summary>
    public partial class LoginWinWiewModel : ObservableObject
    {
        [ObservableProperty]
        private string _userName="admin";
        [ObservableProperty]

        private string _password="123456";
        [ObservableProperty]

        private string _checkCode = string.Empty;

        [ObservableProperty]

        private bool _unLogin=false;


        private readonly IServiceProvider _serviceProvider;
        private INavigationWindow _navigationWindow;
        private readonly IAccountManager _accountService;
        public LoginWinWiewModel(IServiceProvider service, IAccountManager accountService)
        {
            _serviceProvider = service;
            _accountService = accountService;
        }
        [RelayCommand]
        private async Task OnCheckLogin()
        {
            try
            {
                var resp = await _accountService.CheckAccountAsync(UserName, Password, CheckCode);
                if (resp.Code != 1) throw new Exception("登录失败，请检查账户密码！");
                _navigationWindow = (
                _serviceProvider.GetService(typeof(INavigationWindow)) as INavigationWindow)!;
                _navigationWindow!.ShowWindow();
                _navigationWindow.Navigate(typeof(Views.Pages.Home));            
                "登录成功".SnackbarShowInfo();
            }
            catch (Exception ex)
            {
                ex.Message.SnackbarShowError();
            }
            finally
            {
                IWindow loginWin = _serviceProvider.GetRequiredService<IWindow>();
                loginWin.Hide();
            }
        }
    }
}
